/*
 * @author: pizigou
 * @date: 2009-11-5
 */
#include <stdio.h>
#include <sys/time.h>
#include <assert.h> 
#include "handle_file.h"
#include "task.h"

extern char *optarg;
extern int opterr;
extern int optind;
argument arg;

/**
 * calc run time
 */
float time_diff(struct timeval *t_start, struct timeval *t_end)
{
	float s = 1000000*(t_end->tv_sec - t_start->tv_sec) + (t_end->tv_usec - t_start->tv_usec);
	return s/1000000;
}


void useage(const char *name)
{
	printf("usage: %s <options> <args>\n", name);
	printf("options:\n");
	printf("\t-h help\n");
	printf("\t-f data file\n");
	printf("\t-n thread number\n\t   max thread limit to %d\n", MAX_THREAD_NUM);
	printf("\t-p check port number\n");
	printf("\t-d save report path\n");
}

/**
 * parase argument and save
 */
int parse_arg(int argc, char **argv, argument *p_arg)
{
	const char *opt_str = "f:o:n:p:d:h";
	int opt = 0;
	char flag = '\0';

	opterr = 0;
	opt = getopt(argc, argv, opt_str);
	while (opt != -1) {
		switch (opt) {
			case 'f':
				p_arg->data_file = optarg;
				break;
			case 'n':
				p_arg->thread_num = atoi(optarg);
				break;
			case 'p':
				p_arg->port = optarg;
				break;
			case 'd':
				p_arg->dir = optarg;
				break;
			case 'h':
				useage(argv[0]);
				flag = 'h';
				break;
			case '?':
			case 'o':
			default:
				break;
		}
		opt = getopt(argc, argv, opt_str);
	}
	if (p_arg->data_file != NULL && p_arg->thread_num != NULL) return 0;
	else {
		if (flag != 'h') printf("%s -h for help\n", argv[0]);
		return -1;
	}
}

/*
 * read http send info
 */
static int read_http_request_info(char *file, char *buf)
{
	FILE *fp;
	int i = 0;
	if (*(buf + 0) != '\0') return 0;
	fp = fopen(file, "r");
	if (!fp) return -1;
	while ((*(buf + i++) = fgetc(fp)) != EOF);
	fclose(fp);
	return 0;
}

int main(int argc, char **argv)
{
	struct timeval t1,t2;
	int t;
	file f;
	float t_diff;

	if (parse_arg(argc, argv, &arg) != 0) return -1;

	/* 
	 * time start
	 */
	gettimeofday(&t1,NULL);
	
	// read http header from header config file
	memset(arg.http_header, '\0', sizeof(arg.http_header));
	read_http_request_info("http_request.conf", arg.http_header);
	
	f.file_name = arg.data_file;
	f.p_handle_site = dispath_task;
	
	parse_file(&f);

	/* 
	 * time end
	 */
	gettimeofday(&t2,NULL);
	t_diff = time_diff(&t1, &t2);
	//printf("time used:%fs\n", t_diff);

	/*
	 * save result
	 */
	save_state(t_diff);
	return 0;
}
